package mybatis.util;

import static org.mybatis.generator.internal.util.StringUtility.stringContainsSpace;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.JavaTypeResolver;
import org.mybatis.generator.internal.ObjectFactory;
import org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl;

/**
 * JDBC工具类
 * Created by src on 2018/6/25.
 */
public class JdbcUtil {

	// 定义数据库的链接
	private Connection conn;
	// 定义sql语句的执行对象
	private PreparedStatement pstmt;
	// 定义查询返回的结果集合
	private ResultSet rs;

	// 初始化
	public JdbcUtil(String driver, String url, String username, String password) {
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, username, password);
			System.out.println("数据库连接成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 更新数据
	public boolean updateByParams(String sql, List<Object> params) throws SQLException {
		// 影响行数
		int result = -1;
		pstmt = conn.prepareStatement(sql);
		int index = 1;
		// 填充sql语句中的占位符
		if (null != params && !params.isEmpty()) {
			for (int i = 0; i < params.size(); i ++) {
				pstmt.setObject(index ++, params.get(i));
			}
		}
		result = pstmt.executeUpdate();
		return result > 0 ? true : false;
	}

	// 查询多条记录
	public List<Map<String, Object>> selectByParams(String sql, List<Object> params) throws SQLException {
		List<Map<String, Object>> list = new ArrayList<>();
		int index = 1;
		pstmt = conn.prepareStatement(sql);
		if (null != params && !params.isEmpty()) {
			for (int i = 0; i < params.size(); i ++) {
				pstmt.setObject(index++, params.get(i));
			}
		}
		rs = pstmt.executeQuery();
		ResultSetMetaData metaData = rs.getMetaData();
		int colsLen = metaData.getColumnCount();
		while (rs.next()) {
			Map<String, Object> map = new HashMap<>(colsLen);
			for (int i = 0; i < colsLen; i ++) {
				String columnName = metaData.getColumnName(i + 1);
				Object columnValue = rs.getObject(columnName);
				if (null == columnValue) {
					columnValue = "";
				}
				map.put(columnName, columnValue);
			}
			list.add(map);
		}
		return list;
	}

	// 释放连接
	public void release() {
		try {
			if (null != rs) {
                rs.close();
            }
			if (null != pstmt) {
                pstmt.close();
            }
			if (null != conn) {
                conn.close();
            }
		} catch (SQLException e) {
			e.printStackTrace();
		}
		System.out.println("释放数据库连接");
	}

	public String getJavaType(String catalog, String schema, String tableName, String columnName) {
		ResultSet rs = null;
        try {
			rs = conn.getMetaData().getColumns(catalog, schema, tableName, "%");

            List<IntrospectedColumn> columns = new ArrayList<IntrospectedColumn>();
	        while (rs.next()) {
	            IntrospectedColumn introspectedColumn = new IntrospectedColumn();

	            String columnName1 = rs.getString("COLUMN_NAME");
	            if (!columnName.equals(columnName1)) {
	            	continue;
	            }
	            introspectedColumn.setJdbcType(rs.getInt("DATA_TYPE")); //$NON-NLS-1$

	            columns.add(introspectedColumn);
	        }
	        
	        if (!columns.isEmpty()) {
				JavaTypeResolver javaTypeResolver = new JavaTypeResolverDefaultImpl();
	        	return javaTypeResolver.calculateJavaType(columns.get(0)).getShortNameWithoutTypeArguments();
	        }
		} catch (SQLException e) {
			e.printStackTrace();
		} //$NON-NLS-1$
        finally {
            if(rs!=null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        
        return "";
	}
}
